let express = require('express');
let router = express.Router();
//在要解密的后端代码模块中引入jsonwebtoken
let jsonwebtoken = require('jsonwebtoken')

//引入mongoose
let mongoose = require('mongoose');
//引入文件处理代码库
let { uploadFiles } = require('../util/handleFile');
router.post('/avatar', function (req, resp) {
    //配置上传文件信息
    let method = uploadFiles({
        path: './public/images',
        key: 'stuPic',
        size: 30
    });

    method(req, resp, async function (err) {
        if (!err) {
            //上传成功代码
            //获取上传的文件数据
            let file = req.files[0];
            //获取学生编号
            let studentId = req.body.studentId;
            // console.log(`http://127.0.0.1:3000/images/${file.filename}`,studentId);
            let avatar = `http://127.0.0.1:3000/images/${file.filename}`;
            let re = await mongoose.model('studentsModel').updateMany({
                _id: studentId
            }, {
                avatar
            });
            let re2 = await mongoose.model('studentsModel').find({ _id: studentId })
            let token = jsonwebtoken.sign({
                user: re2[0]
            }, 'star', {
                expiresIn: 36000
            })
            if (re.modifiedCount > 0) {
                resp.send({
                    code: 1,
                    message: '修改成功!',
                    data: re2,
                    data2: token
                })
            } else {
                resp.send({
                    code: 3,
                    message: '头像更新失败!请联系管理员!'
                });
            }
        } else {
            //上传失败代码
            resp.send({
                code: 2,
                message: '上传失败!'
            });
        }
    })
});

module.exports = router;